package pub.cleangao.memm.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import pub.cleangao.memm.annotation.RpcServeNode;

import java.util.List;


@Slf4j
public class RpcServiceRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;
    private static final String RPC_SCAN_ATTR = "packageScan";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
        AnnotationAttributes rpcScanAnnotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(RpcServeNode.class.getName()));
        String[] rpcScanBasePackages = new String[0];
        rpcScanBasePackages = rpcScanAnnotationAttributes.getStringArray(RPC_SCAN_ATTR);
        if (rpcScanBasePackages.length != 0) {
            log.info("Rpc using canonical package: {}", List.of(rpcScanBasePackages));
        }
        if (rpcScanBasePackages.length == 0) {
            rpcScanBasePackages = new String[]{((StandardAnnotationMetadata) importingClassMetadata).getIntrospectedClass().getPackage().getName()};
            log.info("Rpc using default package: {}", List.of(rpcScanBasePackages));
        }
        RpcServiceScanner rpcServiceScanner = new RpcServiceScanner(registry);
        rpcServiceScanner.setResourceLoader(resourceLoader);
        int rpcServiceCount = rpcServiceScanner.scan(rpcScanBasePackages);
        log.info("Rpc service class impl-count: [{}]", rpcServiceCount);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


}
